<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .progress {
        border: solid;
        > div {
          height: 20px;
          background-color: blue;
          width: 0;
          color: white;
          text-align: center;
        }
      }
    </style>
  </head>
  <body>
    <div id="tip"></div>
    <form name="form">
      <input name="file" type="file" />
      <button type="button" id="upBtn">上传</button>
    </form>
    <div class="progress">
      <div id="progressBar"></div>
    </div>
    <script>
      upBtn.onclick = function () {
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "http://127.0.0.1:8081/up");

        xhr.onload = function () {
          console.log(xhr.response);
          progressBar.innerHTML = "上传成功";
        };

        //上传进度事件
        xhr.upload.onprogress = function (e) {
          const r = (e.loaded / e.total) * 100 + "%";
          progressBar.style.width = r;
        };

        xhr.upload.onloadstart = function () {
          tip.innerHTML = "上传开始";
        };

        xhr.upload.ontimeout = function () {
          // 设置 xhr.ontimeout
          tip.innerHTML = "超时";
        };
        xhr.upload.onerror = function () {
          tip.innerHTML = "网络错误";
        };
        xhr.upload.onload = function () {
          tip.innerHTML = "上传成功";
        };
        xhr.upload.onloadend = function () {
          tip.innerHTML = "上传结束";
        };
        //----
        const fd = new FormData();
        fd.append("myfile", form.file.files[0]);
        fd.append("name", "jack");
        fd.append("age", 20);
        xhr.send(fd);
      };
    </script>
  </body>
</html>
